package com.lai.hospital.config;

import cn.hutool.json.JSONObject;
import com.aliyun.ocr_api20210707.Client;
import com.aliyun.ocr_api20210707.models.RecognizeIdcardResponse;
import com.aliyun.ocr_api20210707.models.RecognizeIdcardResponseBody;
import com.aliyun.tea.*;
import com.aliyun.ocr_api20210707.models.RecognizeIdcardRequest;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * @author : lai
 * @version V1.0
 * @Project: hospital-springboot
 * @Package com.lai.hospital.config
 * @Description: 文字识别配置
 * @date Date : 2023年02月19日 2:13
 */
@Configuration
public class OCRConfig {

    @Value("${alicloud.accessKey}")
    private String accessKey;

    @Value("${alicloud.secretKey}")
    private String secretKey;

    @Value("${alicloud.endpoint}")
    private String endpoint;

    @Bean
    public Client createOCRClient() throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKey)
                // 您的AccessKey Secret
                .setAccessKeySecret(secretKey);
                // 访问的域名
        config.endpoint = endpoint;
        return new Client(config);
    }

    public RecognizeIdcardResponseBody OCR(MultipartFile file) throws Exception {
        Client ocrClient = createOCRClient();
 
        InputStream bodyStream = file.getInputStream();
        RecognizeIdcardRequest recognizeIdcardRequest = new RecognizeIdcardRequest()
                .setOutputFigure(true)
                .setOutputQualityInfo(false)
                .setBody(bodyStream);
        RuntimeOptions runtimeOptions = new RuntimeOptions();
        RecognizeIdcardResponse recognizeIdcardResponse = null;
        try {
            // 复制代码运行请自行打印 API 的返回值
            recognizeIdcardResponse = ocrClient.recognizeIdcardWithOptions(recognizeIdcardRequest, runtimeOptions);
            return recognizeIdcardResponse.getBody();
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return recognizeIdcardResponse.getBody();
    }
}
